<?php

/**
 * ECSHOP 专题管理
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: topic.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

/* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $_REQUEST['act'] = 'list';
}
else
{
    $_REQUEST['act'] = trim($_REQUEST['act']);
}
require_once(ROOT_PATH . 'includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);
$exc = new exchange($ecs->table('second'), $db, 'second_id','');
/* 配置风格颜色选项 */

$allow_suffix = array('gif', 'jpg', 'png', 'jpeg', 'bmp', 'swf');

/*------------------------------------------------------ */
//-- 专题列表页面
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
    admin_priv('second');

    $smarty->assign('ur_here',     $_LANG['17_second']);

    $smarty->assign('full_page',   1);
    $list = get_second_list();

    $smarty->assign('second_list',   $list['item']);
    $smarty->assign('filter',       $list['filter']);
    $smarty->assign('record_count', $list['record_count']);
    $smarty->assign('page_count',   $list['page_count']);

    $sort_flag  = sort_flag($list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    assign_query_info();
    $smarty->assign('action_link', array('text' => '添加专题', 'href' => 'second.php?act=add'));
    $smarty->display('second_list.htm');
}
/* 添加,编辑 */
if ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    admin_priv('second');

    $isadd     = $_REQUEST['act'] == 'add';
    $smarty->assign('isadd', $isadd);
    $second_id  = empty($_REQUEST['second_id']) ? 0 : intval($_REQUEST['second_id']);

    include_once(ROOT_PATH.'includes/fckeditor/fckeditor.php'); // 包含 html editor 类文件

    $smarty->assign('ur_here',     $_LANG['17_second']);
    $smarty->assign('action_link', list_link($isadd));

    $smarty->assign('cat_list',   cat_list(0, 1));
    $smarty->assign('brand_list', get_brand_list());
    $smarty->assign('cfg_lang',   $_CFG['lang']);
    require(ROOT_PATH . 'includes/cls_json.php');
    $json          = new JSON;
    if (!$isadd)
    {
        $sql = "SELECT * FROM " . $ecs->table('second') . " WHERE second_id = '$second_id'";
        $topic = $db->getRow($sql);
        $topic['start_time'] = local_date('Y-m-d', $topic['start_time']);
        $topic['end_time']   = local_date('Y-m-d', $topic['end_time']);
        
        
        $topic['data'] = addcslashes($topic['data'], "'");
        $topic['data'] = $json->encode(@unserialize($topic['data']));
        $topic['data'] = addcslashes($topic['data'], "'");


        $smarty->assign('topic', $topic);
        $smarty->assign('act',   "update");
    }
    else
    {
        $topic = array('title' => '','data'=>'[]');
        $smarty->assign('topic', $topic);
        $smarty->assign('act', "insert");
    }
    $smarty->display('second_edit.htm');
}
elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
    admin_priv('second');

    $is_insert = $_REQUEST['act'] == 'insert';
    $second_id  = empty($_POST['second_id']) ? 0 : intval($_POST['second_id']);
   
    if ($_FILES['img']['size']>0)
    {
    	/* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
    	if (isset($_FILES['img']['error'])) // php 4.2 版本才支持 error
    	{
    		// 最大上传文件大小
    		$php_maxsize = ini_get('upload_max_filesize');
    		$htm_maxsize = '2M';
    	
    	
    		if ($_FILES['img']['error'] == 0)
    		{
    			if (!$image->check_img_type($_FILES['img']['type']))
    			{
    				sys_msg('图片格式不正确！', 1, array(), false);
    			}
    		}
    		elseif ($_FILES['img']['error'] == 1)
    		{
    			sys_msg('图片文件太大了（最大值：'.$php_maxsize.'），无法上传。', 1, array(), false);
    		}
    		elseif ($_FILES['img']['error'] == 2)
    		{
    			sys_msg('图片文件太大了（最大值：'.$htm_maxsize.'），无法上传。', 1, array(), false);
    		}
    	
    	
    	}
    	/* 4.1版本 */
    	else
    	{
    		if ($_FILES['img']['tmp_name'] != 'none')
    		{
    			if (!$image->check_img_type($_FILES['img']['type']))
    			{
    	
    				sys_msg('图片格式不正确！', 1, array(), false);
    			}
    		}
    	
    	
    	}
    	
    	
    	$original_img   = $image->upload_image($_FILES['img'],'afficheimg/'.date('Ymd')); // 原始图片
    	 
    	if ($original_img === false)
    	{
    		sys_msg($image->error_msg(), 1, array(), false);
    	}
    }
    else $original_img = '';
 
    //手机版图片
    if ($_FILES['img_wap']['size']>0)
    {
    	/* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
    	if (isset($_FILES['img_wap']['error'])) // php 4.2 版本才支持 error
    	{
    		// 最大上传文件大小
    		$php_maxsize = ini_get('upload_max_filesize');
    		$htm_maxsize = '2M';
    		 
    		 
    		if ($_FILES['img_wap']['error'] == 0)
    		{
    			if (!$image->check_img_type($_FILES['img_wap']['type']))
    			{
    				sys_msg('图片格式不正确！', 1, array(), false);
    			}
    		}
    		elseif ($_FILES['img_wap']['error'] == 1)
    		{
    			sys_msg('图片文件太大了（最大值：'.$php_maxsize.'），无法上传。', 1, array(), false);
    		}
    		elseif ($_FILES['img_wap']['error'] == 2)
    		{
    			sys_msg('图片文件太大了（最大值：'.$htm_maxsize.'），无法上传。', 1, array(), false);
    		}
    		 
    		 
    	}
    	/* 4.1版本 */
    	else
    	{
    		if ($_FILES['img_wap']['tmp_name'] != 'none')
    		{
    			if (!$image->check_img_type($_FILES['img_wap']['type']))
    			{
    				 
    				sys_msg('图片格式不正确！', 1, array(), false);
    			}
    		}
    		 
    		 
    	}
    	 
    	 
    	$original_img_wap   = $image->upload_image($_FILES['img_wap'],'afficheimg/'.date('Ymd')); // 原始图片
    
    	if ($original_img_wap === false)
    	{
    		sys_msg($image->error_msg(), 1, array(), false);
    	}
    }
    else $original_img_wap = '';

    
    
    

    require(ROOT_PATH . 'includes/cls_json.php');

    $start_time = local_strtotime($_POST['start_time']);
    $end_time   = local_strtotime($_POST['end_time']);

    $json       = new JSON;
    $tmp_data   = $json->decode($_POST['second_data']);
    
    
    $data       = serialize($tmp_data);
    $base_style = $_POST['base_style'];
    $keywords   = $_POST['keywords'];
    $description= $_POST['description'];
    $content = $_POST['content'];

    if ($is_insert)
    {
        $sql = "INSERT INTO " . $ecs->table('second') . " (title,start_time,end_time,data,img,keywords,description,content,img_wap)" .
                "VALUES ('$_POST[topic_name]','$start_time','$end_time','$data', '$original_img','$keywords','$description','$content','$original_img_wap')";
        admin_log($_POST['topic_name'], 'add', 'second');
    }
    else
    {
    	if (!empty($original_img))
    	{
    		/* 删除原来的图片文件 */
    		$sql = "SELECT img " .
    				" FROM " . $ecs->table('second') .
    				" WHERE second_id = '$_POST[second_id]'";
    		$row = $db->getRow($sql);
    		if ($row['img'] != '' && is_file('../' . $row['img']))
    		{
    			@unlink('../' . $row['img']);
    		}
    		
    		$sql = "UPDATE " . $ecs->table('second') .
                "SET img='$original_img' WHERE second_id='$second_id' LIMIT 1";
    		$db->query($sql);
    	}
    	
    	if (!empty($original_img_wap))
    	{
    		/* 删除原来的图片文件 */
    		$sql = "SELECT img_wap " .
    				" FROM " . $ecs->table('second') .
    				" WHERE second_id = '$_POST[second_id]'";
    		$row = $db->getRow($sql);
    		if ($row['img_wap'] != '' && is_file('../' . $row['img_wap']))
    		{
    			@unlink('../' . $row['img_wap']);
    		}
    	
    		$sql = "UPDATE " . $ecs->table('second') .
    		"SET img_wap='$original_img_wap' WHERE second_id='$second_id' LIMIT 1";
    		$db->query($sql);
    	}
    	
    	
        $sql = "UPDATE " . $ecs->table('second') .
                "SET title='$_POST[topic_name]',start_time='$start_time',end_time='$end_time',data='$data', keywords='$keywords', description='$description',content='$content'" .
               " WHERE second_id='$second_id' LIMIT 1";
        
        /* 删除second_goods表的记录 */
        $db->query('DELETE FROM '.$ecs->table('second_goods').' WHERE second_id = '.$second_id);
        admin_log($_POST['topic_name'], 'edit', 'second');
    }

    $db->query($sql);
    $id = $is_insert ? $db->insert_id() : $second_id;
    /* 商品插入表 */
    if (is_array($tmp_data)){
    	foreach ($tmp_data as $k=>$v){
    		$tmp_arr = explode('|', $v);
    		$goods_id = intval($tmp_arr[1]);
    		$goods_price = floatval($tmp_arr[2]);
    		$goods_number = empty($tmp_arr[3])?0:intval($tmp_arr[3]);
    		/* 当存在该商品的记录时才插入表  */
    		if ($db->getOne('SELECT 1 FROM '.$ecs->table('goods').' WHERE goods_id='.$goods_id.' LIMIT 1')){
    			$sql = 'INSERT INTO '.$ecs->table('second_goods').' (second_id,goods_id,goods_price,goods_number)VALUES ('.$id.','.$goods_id.','.$goods_price.','.$goods_number.')';
    			$db->query($sql);
    		}
    		
    	}
    }
    

    clear_cache_files();

    $links[] = array('href' => 'second.php', 'text' =>  $_LANG['back_list']);
    sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST['act'] == 'get_goods_list')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_second_goods_list($filters);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value' => $val['goods_id'],
                       'text'  => $val['goods_name'],
        				'data' => $val['shop_price'],
        				'num'	=> $val['goods_number']
        );
    }

    make_json_result($opt);
}
elseif ($_REQUEST["act"] == "delete")
{
    admin_priv('second');

    
    $sql = "DELETE FROM " . $ecs->table('second') . " WHERE ";
    $sql2 = "DELETE FROM ".$ecs->table('second_goods')." WHERE ";

    if (!empty($_POST['checkboxs']))
    {
        $sql .= db_create_in($_POST['checkboxs'], 'second_id');
        $sql2 .= db_create_in($_POST['checkboxs'], 'second_id');
        $titleArr = $db->getCol('SELECT title FROM '.$ecs->table('second').' WHERE '.db_create_in($_POST['checkboxs'], 'second_id'));
        $title = implode(',',$titleArr);
    }
    elseif (!empty($_GET['id']))
    {
    	
        $_GET['id'] = intval($_GET['id']);
        $sql .= "second_id = '$_GET[id]'";
        $sql2 .= "second_id = '$_GET[id]'";
        $title = $db->getOne('SELECT title FROM '.$ecs->table('second').' WHERE second_id='.$_GET['id']);
    }
    else
    {
        exit;
    }

    $db->query($sql);
    $db->query($sql2);

    clear_cache_files();
    admin_log($title, 'remove', 'second');
    if (!empty($_REQUEST['is_ajax']))
    {
        $url = 'second.php?act=query&' . str_replace('act=delete', '', $_SERVER['QUERY_STRING']);
        ecs_header("Location: $url\n");
        exit;
    }
    
    $links[] = array('href' => 'second.php', 'text' =>  $_LANG['back_list']);
    sys_msg('操作成功', 0, $links);
}
elseif ($_REQUEST["act"] == "query")
{
    $topic_list = get_second_list();
    $smarty->assign('second_list',   $topic_list['item']);
    $smarty->assign('filter',       $topic_list['filter']);
    $smarty->assign('record_count', $topic_list['record_count']);
    $smarty->assign('page_count',   $topic_list['page_count']);
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);

    /* 排序标记 */
    $sort_flag  = sort_flag($topic_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    $tpl = 'second_list.htm';
    make_json_result($smarty->fetch($tpl), '',array('filter' => $topic_list['filter'], 'page_count' => $topic_list['page_count']));
}
elseif ($_REQUEST['act'] == 'toggle_selected')
{
	check_authz_json('second');

	$second_id       = intval($_POST['id']);
	$is_selected        = intval($_POST['val']);

	if ($exc->edit("is_selected = '$is_selected'", $second_id))
	{
		clear_cache_files();
		make_json_result($is_selected);
	}
}

/**
 * 获取专题列表
 * @access  public
 * @return void
 */
function get_second_list()
{
    $result = get_filter();
    if ($result === false)
    {
        /* 查询条件 */
        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'second_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $sql = "SELECT COUNT(*) FROM ".$GLOBALS['ecs']->table('second');
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('second'). " ORDER BY $filter[sort_by] $filter[sort_order]";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $query = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    $res = array();

    while($second = $GLOBALS['db']->fetch_array($query)){
        $second['start_time'] = local_date('Y-m-d',$second['start_time']);
        $second['end_time']   = local_date('Y-m-d',$second['end_time']);
        $second['url']        = $GLOBALS['ecs']->url() . 'second.php?second_id=' . $second['topic_id'];
        $res[] = $second;
    }

    $arr = array('item' => $res, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}

/**
 * 列表链接
 * @param   bool    $is_add     是否添加（插入）
 * @param   string  $text       文字
 * @return  array('href' => $href, 'text' => $text)
 */
function list_link($is_add = true, $text = '')
{
    $href = 'second.php?act=list';
    if (!$is_add)
    {
        $href .= '&' . list_link_postfix();
    }
    if ($text == '')
    {
        $text = '专题列表';
    }

    return array('href' => $href, 'text' => $text);
}

/**
 * 取得秒杀商品列表
 * @param   object  $filters    过滤条件
 */
function get_second_goods_list($filter)
{
	$filter->keyword = json_str_iconv($filter->keyword);
// 	$where = get_where_sql($filter); // 取得过滤条件
	$where  = isset($filter->is_delete) && $filter->is_delete == '1' ?
	' WHERE g.is_delete = 1 ' : ' WHERE g.is_delete = 0 ';
	$where .= isset($filter->cat_id) && $filter->cat_id > 0 ? ' AND ' . get_children($filter->cat_id) : '';
	$where .= isset($filter->brand_id) && $filter->brand_id > 0 ? " AND g.brand_id = '" . $filter->brand_id . "'" : '';
	$where .= isset($filter->keyword) && trim($filter->keyword) != '' ?
	" AND (g.goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR g.goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR g.goods_id LIKE '%" . mysql_like_quote($filter->keyword) . "%') " : '';
	
	/* 取得数据 */
	$sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.goods_number-g.frozen AS goods_number '.
			'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
			$where .
			'LIMIT 50';
	$row = $GLOBALS['db']->getAll($sql);

	return $row;
}

?>
